package com.linskating.wheat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.linskating.wheat.annotations.aop.LogOperation;
import com.linskating.wheat.common.BaseResponse;
import com.linskating.wheat.common.ErrorCode;
import com.linskating.wheat.common.ResultUtils;
import com.linskating.wheat.constant.UserConstant;
import com.linskating.wheat.exception.BusinessException;
import com.linskating.wheat.model.domain.Team;
import com.linskating.wheat.model.domain.User;
import com.linskating.wheat.model.domain.UserTeam;
import com.linskating.wheat.model.dto.TeamQuery;
import com.linskating.wheat.model.request.teamRequest.*;
import com.linskating.wheat.model.vo.TeamUserVO;
import com.linskating.wheat.service.TeamService;
import com.linskating.wheat.service.UserService;
import com.linskating.wheat.service.UserTeamService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@CrossOrigin(origins = "http://localhost:5173", methods = {RequestMethod.GET, RequestMethod.POST}, allowCredentials = "true")
@LogOperation
public class TeamController implements UserConstant {

    @Resource
    private UserService userService;

    @Resource
    private TeamService teamService;

    @Resource
    private UserTeamService userTeamService;

    // 创建队伍
    @PostMapping("/create")
    public BaseResponse<Long> createTeam(@RequestBody TeamCreatRequest teamCreatRequest, HttpServletRequest request) {
        if (teamCreatRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User currentUser = userService.currentUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamCreatRequest, team);
        return ResultUtils.success(teamService.creatTeam(team, currentUser));
    }

    // 删除队伍, 仅管理员可以删除
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody TeamDeleteRequest teamDeleteRequest, HttpServletRequest request) {
        if (teamDeleteRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long teamId = teamDeleteRequest.getId();
        if (teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.currentUser(request);
        boolean result = teamService.deleteTeam(teamId, userService.isNotAdmit(currentUser));
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除队伍失败");
        }
        return ResultUtils.success(true);
    }

    // 更新队伍
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest updateRequest, HttpServletRequest request) {
        if (updateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.currentUser(request);
        boolean result = teamService.updateTeam(updateRequest, currentUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新队伍失败");
        }
        return ResultUtils.success(true);
    }

    // 获取队伍列表
    @PostMapping("/get/list")
    public BaseResponse<List<TeamUserVO>> getTeamList(@RequestBody TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<TeamUserVO> list = teamService.listTeam(teamQuery, userService.isNotAdmit(request));
        return ResultUtils.success(list);
    }

    // 获取我创建的队伍的所有信息
    @PostMapping("/get/list/creat")
    public BaseResponse<List<TeamUserVO>> getMyCreatTeamList(@RequestBody TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User currentUser = userService.currentUser(request);
        teamQuery.setUserId(currentUser.getId());
        teamQuery.setIsExpireTimeActive(false);
        List<TeamUserVO> teamUserVOList = teamService.listTeam(teamQuery, false);
        return ResultUtils.success(teamUserVOList);
    }

    // 获取我加入的队伍所有信息
    @PostMapping("/get/list/join")
    public BaseResponse<List<TeamUserVO>> getMyJoinTeamList(@RequestBody TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User currentUser = userService.currentUser(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", currentUser.getId());
        // 防止脏数据,去重
        Set<Long> teamIdSet = userTeamService.list(queryWrapper).stream().collect(Collectors.groupingBy(UserTeam::getTeamId)).keySet();
        teamQuery.setIdList(new ArrayList<>(teamIdSet));
        teamQuery.setIsExpireTimeActive(false);
        List<TeamUserVO> teamUserVOList = teamService.listTeam(teamQuery, false);
        return ResultUtils.success(teamUserVOList);
    }

    // 分页获取所有队伍列表
    @PostMapping("/get/page")
    public BaseResponse<Page<TeamUserVO>> getTeamPage(@RequestBody TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.currentUser(request);
        Page<TeamUserVO> resultPage = teamService.getTeamPage(teamQuery.getThePageNum(), teamQuery.getPageSize(), currentUser.getId());
        return ResultUtils.success(resultPage);
    }

    // 加入队伍
    @PostMapping("/joinTeam")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User currentUser = userService.currentUser(request);
        boolean result = teamService.joinTeam(teamJoinRequest, currentUser);
        return ResultUtils.success(result);
    }

    @GetMapping("/totalCount")
    public BaseResponse<Long> totalCount(HttpServletRequest request) {
        Long userId = userService.currentUser(request).getId();
        Long count = teamService.totalCount(userId);
        return ResultUtils.success(count);
    }

    // 用户退出队伍
    @PostMapping("/quitTeam")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User currentUser = userService.currentUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, currentUser);
        return ResultUtils.success(result);
    }

    // 队长解散队伍
    @PostMapping("/dismissTeam")
    public BaseResponse<Boolean> dismissTeam(@RequestBody TeamDismissRequest teamDismissRequest, HttpServletRequest request) {
        if (teamDismissRequest == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User currentUser = userService.currentUser(request);
        boolean result = teamService.dismissTeam(teamDismissRequest, currentUser);
        return ResultUtils.success(result);
    }

}
